<?php


namespace app\common\model;

class Shops extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_shops';
    // 主键ID
    protected $pk = 'shop_id';

	/**
	 * 获取线上店铺信息
	 * @param $shop_id
	 * @return Shops|array|mixed|\PDOStatement|string|\think\db\Query|\think\Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	function getOneShop($shop_id,$item = 'shop_id,shop_name',$is_online = true){
	    $is_online?$type = [1,3]:$type = [2,3];
		$where = [
			['approved','=',1],
			['state','=',1],
			['shop_id','=',$shop_id],
            ['shop_type','in',$type],
		];
		return $this->field($item)->where($where)->find();
	}

	// 获取列表
	function get_list($cond,$orderby = "",$item = "*")
	{
		$where = null;

		if(!empty($cond['approved'])){
			$where[] = ['approved', '=',$cond['approved']];
		}


		if(!empty($cond['state'])){
			$where[] = ['state', '=',$cond['state']];
		}
		if(!empty($cond['shop_ids'])){
			$where[] = ['shop_id', 'in',$cond['shop_ids']];
		}

		$rs = $this
			->field($item)
			->where($where)
			->order($orderby)
			->select();
		return $rs;
	}

    // 获取分页列表
    function get_list_page($cond,$orderby,$item,$limit)
    {
        $where = null;
        if(!empty($cond['shop_name'])){
            $where[] = ['shop_name','like',"%".$cond['shop_name']."%"];
        }

        if(!empty($cond['shop_id'])){
            $where[] = ['shop_id', '=',$cond['shop_id']];
        }

        if(!empty($cond['approved'])){
            $where[] = ['approved', '=',$cond['approved']];
        }

        if(!empty($cond['state'])){
            $where[] = ['state', '=',$cond['state']];
        }

		if(!empty($cond['shop_type'])){
			$where[] = ['shop_type', '=',$cond['shop_type']];
		}

		if(!empty($cond['shop_types'])){
			$where[] = ['shop_type', 'in',$cond['shop_types']];
		}

        $rs = $this
            ->field($item)
            ->alias('s')
            ->where($where)
            ->order($orderby)
            ->paginate($limit)
            ->each(function($item){
                $item['address'] = trim($item['address']);
                return $item;
            });
        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['shop_id' => $id];
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            // 更新数据
            $this->allowField(true)->save($params);
            $rs = $this->shop_id;
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

}